package com.mediacloud.app.newsmodule.fragment.album;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Parcelable;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.mediacloud.app.assembly.interfaces.LoadNetworkBack;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.views.LikeBadgeView;
import com.mediacloud.app.assembly.views.XRefreashListView;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.TopicDetailDataReciver;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.AlbumAudioActivity;
import com.mediacloud.app.newsmodule.activity.AlbumPlayActivity;
import com.mediacloud.app.newsmodule.adaptor.album.AlbumListAdapter;
import com.mediacloud.app.newsmodule.adaptor.comment.x.XCommentActivity;
import com.mediacloud.app.newsmodule.addnewslike.m.AddLikeDataInvoke;
import com.mediacloud.app.newsmodule.addnewslike.p.NewsLikePresenter;
import com.mediacloud.app.newsmodule.addnewslike.v.ILikesNumUpdate;
import com.mediacloud.app.newsmodule.interfaces.AlbumClickCall;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.newsmodule.utils.support.SupportKit;
import com.mediacloud.app.newsmodule.view.BadgeView;
import com.mediacloud.app.newsmodule.view.CommentInputView;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.model.UserInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yoake on 2016/12/23.
 */

public class AlbumFragment extends BaseFragment implements AlbumClickCall, ILikesNumUpdate {
    private View bottomCommentLayout;
    private CommentInputView commentInputView;
    private BadgeView badgeView;
    private TextView letmeSay;
    private View letmeSaybtn;
    private AlbumListAdapter adapter;
    private int pageIndex = 1;
    private int perPageSize = 6;
    private boolean isLoadMore = false;
    private TextView albumTitle;
    private LikeBadgeView albumLikeBadgeView;
//    private ImageView album_like_imageview;
//    protected BadgeView album_like_badgeView;
    private TextView albumPlaying;
    private XRefreashListView listView;
    public ArticleItem item;
    private String id;
    private AlbumClickCall call;
    //    private int position;
    private int lastItemid;
    private boolean checkPosition = true;
    private String title;
    protected ImageButton mBtn_share;
    NewsLikePresenter newsLikePresenter;
    private ShareWrap shareWrap;
//    protected ShareGridDataUtil shareGridDataUtil;
//    protected SharePopGridWindow sharePopGridWindow;

    @Override
    public int getLayoutResID() {
        return R.layout.album_fragment_layout;
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        id = createBundle.getString("id");
//        position = createBundle.getInt("position", 0);
        lastItemid = createBundle.getInt("lastItemid", -1);
        title = createBundle.getString("title", "");
    }


    @Override
    public void initView() {
        commentInputView = Utility.findViewById(mRootView, R.id.commentInputView);
        bottomCommentLayout = Utility.findViewById(mRootView, R.id.bottomCommentLayout);
        letmeSay = Utility.findViewById(mRootView, R.id.letmeSay);
        letmeSaybtn = Utility.findViewById(mRootView, R.id.letmeSaybtn);
        mBtn_share = Utility.findViewById(mRootView, R.id.btn_share);
        albumTitle = Utility.findViewById(mRootView, R.id.albumTitle);
        albumLikeBadgeView = Utility.findViewById(mRootView, R.id.album_like_badgeView);
        albumLikeBadgeView.setNeedNewIcon(true);
//        album_like_imageview = Utility.findViewById(mRootView, R.id.album_like_imageview);
//        album_like_badgeView = new BadgeView(album_like_imageview.getContext());
//        album_like_badgeView.setTargetView(album_like_imageview);
//        album_like_badgeView.setBackground(8f, AppFactoryGlobalConfig.getAppServerConfigInfo(album_like_imageview.getContext()).getMainColor());
//        album_like_badgeView.setVisibility(View.GONE);
        initShare();
        boolean openLikeBtn =AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getOtherFunction()!=null&&AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getOtherFunction().getSupport()>0;// "1".equals(getActivity().getResources().getString(R.string.openLikeBtn));

        if (!openLikeBtn) {
            albumLikeBadgeView.setVisibility(View.GONE);
//            album_like_imageview.setVisibility(View.GONE);
//            album_like_badgeView.setVisibility(View.GONE);
        }else {
            albumLikeBadgeView.setVisibility(View.VISIBLE);
        }

        String currentTenantid = getResources().getString(R.string.tenantid);
        if (currentTenantid.equals(getResources().getString(R.string.tenant_jiangxi))) {
            mBtn_share.setVisibility(View.GONE);
        }
        mBtn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item != null) {
                   // sharePopGridWindow.setShareGridAdaptorData(shareGridDataUtil.BaseShareGridData);
                    shareWrap.show(v);
                }
            }
        });
        albumPlaying = Utility.findViewById(mRootView, R.id.album_playingTitle);
        listView = Utility.findViewById(mRootView, R.id.albumListView);
        letmeSay = Utility.findViewById(mRootView, R.id.letmeSay);
        commentInputView = Utility.findViewById(mRootView, R.id.commentInputView);
        albumTitle.setText(title);
        if (getActivity() instanceof AlbumPlayActivity) {
            call = ((AlbumPlayActivity) getActivity()).call;
        } else if (getActivity() instanceof AlbumAudioActivity) {
            call = ((AlbumAudioActivity) getActivity()).call;
        }
        newsLikePresenter = new NewsLikePresenter(getActivity(), this);
        initListView();
    }

    protected void initShare() {
        shareWrap =new  ShareWrap(requireContext(),false);
        shareWrap.setShowFunction(true);
        shareWrap.init(item,new CatalogItem());
//        shareGridDataUtil = new SBShareUtils();
//        sharePopGridWindow = new SharePopGridWindow(getActivity());
//        sharePopGridWindow.setShareGirdListener(this);
//        shareGridDataUtil.initBaseShareGridData(getActivity());
//        sharePopGridWindow.setShareGridAdaptorData(shareGridDataUtil.BaseShareGridData);
    }

    @Override
    protected void initOther() {
        super.initOther();
        badgeView = new BadgeView(getActivity());
        /***
         * 查看评论列表
         */
        letmeSaybtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intoComment();
            }
        });
        /**
         * 封装评论功能的View_提交监听
         */
        commentInputView.commentListener = new CommentInputView.SubmitCommentListener() {
            @Override
            public void success() {
                hideInputComment();
            }

            @Override
            public void failed() {
            }
        };
        /**
         * 封装评论功能的View_取消监听
         */
        commentInputView.cancelComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputComment();
            }
        });
        /**
         * 发表评论Layout的监听
         */
        letmeSay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                bottomCommentLayout.setVisibility(View.GONE);
                commentInputView.setVisibility(View.VISIBLE);
                commentInputView.show();
            }
        });
    }

    /**
     * 初始化ListView
     */
    protected void initListView() {
        View mView = View.inflate(getActivity(), R.layout.album_wangqi_layout, null);
        View line = mView.findViewById(R.id.viewLine);
        String colorString = AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getColor();
        line.setBackgroundColor(Color.parseColor(colorString));
        listView.addHeaderView(mView);
        listView.setPullRefreshEnable(true);
        listView.setPullLoadEnable(false);
        listView.setXListViewListener(new XRefreashListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                isLoadMore = false;
                getAlbumDetail();
            }

            @Override
            public void onLoadMore() {
                pageIndex++;
                isLoadMore = true;
                getAlbumDetail();
            }
        });
        adapter = new AlbumListAdapter(getActivity(), this);
        listView.setAdapter(adapter);
        getAlbumDetail();
    }

    /**
     * 获取专辑详情以及列表
     */

    protected void getAlbumDetail() {
        DataInvokeUtil.getTopicDetailById(id, pageIndex, perPageSize, new LoadNetworkBack<TopicDetailDataReciver>() {
            @Override
            public void Success(TopicDetailDataReciver result) {
                listView.stopLoadMore();
                listView.stopRefresh();
                listView.setPullLoadEnable(result.more);
                if (isLoadMore) {
                    adapter.addDatas(result.articleList);
                } else {
                    if (checkPosition) {
                        checkPosition(result.articleList);
                        checkPosition = false;
                    }
                    adapter.setDatas(result.articleList);
                }
            }

            @Override
            public void Failure(Object obj) {
                listView.stopLoadMore();
                listView.stopRefresh();
            }

            @Override
            public void otherData(String result) {
                listView.stopLoadMore();
                listView.stopRefresh();
            }
        }, new TopicDetailDataReciver());

    }

    /**
     * 检测列表中正在播放音频的位置
     *
     * @param articleList
     */
    protected void checkPosition(List<ArticleItem> articleList) {
        for (int i = 0; i < articleList.size(); i++) {
            if (lastItemid == articleList.get(i).getId()) {
                adapter.setChose(i);
            }
        }
    }

    /**
     * 显示评论窗口，隐藏输入框
     */
    protected void hideInputComment() {
        bottomCommentLayout.setVisibility(View.VISIBLE);
        commentInputView.setVisibility(View.GONE);
        commentInputView.hide();
    }

    /**
     * 跳转评论列表页
     */
    protected void intoComment() {
        if (FunKt.isFastClick()){
            Intent intent = new Intent();
            intent.putExtra("data", item);
            intent.setClass(getActivity(), XCommentActivity.class);
            startActivity(intent);
        }

    }


    @Override
    public void clickItem(Parcelable p) {
        item = (ArticleItem) p;
        setCommentView();
        albumPlaying.setText(item.getTitle());
        SupportKit.INSTANCE.initSupportViewState(requireContext(),SupportKit.TYPE_1,""+item.getId(),albumLikeBadgeView);
        call.clickItem(item);
      //  mediacloud.appAgent(getActivity(), item);
        boolean openLikeBtn =AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getOtherFunction()!=null&&AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getOtherFunction().getSupport()>0;// "1".equals(getActivity().getResources().getString(R.string.openLikeBtn));
        if (openLikeBtn)
            like();
    }

    /**
     * 详情页点击统计
     *
     * @param context
     * @param articleItem
     */
    private void mediacloudAppAgent(Context context, ArticleItem articleItem) {
        if (!AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.needUserBehavior)
            return;
        UserInfo user = UserInfo.getUserInfo(context);
        Map<String, String> values = new HashMap<>();
        values.put("tenant", context.getResources().getString(R.string.tenantid));
        values.put("act_obj", articleItem.getId() + "");
        if (UserInfo.isLogin(context)) {
            values.put("user_id", user.getUserid());
        } else {
            values.put("user_id", "0");
        }
    //    AppAgent.onHaiHeEvent(context, values);
    }

    public void like() {
        if (item == null) {
            albumLikeBadgeView.setEnabled(false);
            return;
        } else {
            albumLikeBadgeView.setEnabled(true);
        }
        NewsLikePresenter.initLikes(newsLikePresenter.addLikeDataInvoke, albumLikeBadgeView, albumLikeBadgeView.getBadgeTextView(),
                item, getActivity(),1);
    }

    /**
     * 设置显示评论数
     */
    private void setCommentView() {
        badgeView.setText("");
        if ("1".equals(item.getIsComment()) && AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getIs_member() > 0)//&&AppFactoryGlobalConfig.getAppServerConfigInfo(this).isAllowShowComment()
        {
            bottomCommentLayout.setVisibility(View.VISIBLE);
            badgeView.setTargetView(letmeSaybtn);
            badgeView.setBadgeCount(-7);
            badgeView.setText(item.getCommentCount() + "");
            commentInputView.articleItem = item;
        } else {
            bottomCommentLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void updateLikesNum(int value) {

    }

    @Override
    public void updateLikesSuccess(AddLikeDataInvoke.AddLikeDataReciver data) {

        try {
            int likes = Integer.parseInt(albumLikeBadgeView.getBadgeTextView().getText().toString());
            if (item.getIsSupport()) {
                //点赞
                if (data.state) {
                    likes++;
                    albumLikeBadgeView.setBadgeText(String.valueOf(likes));
//                    ToastUtil.show(albumLikeBadgeView.getContext(), R.string.dianzan_true);
                    if (AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getCancelSupport() == 0) {
                        albumLikeBadgeView.setSelected(false);
                    } else {
                        albumLikeBadgeView.setSelected(true);
                    }
                } else {
                    updateLikesFault(null);
                    return;
                }
            } else {
                //取消点赞s
                if (data.state) {
                    likes--;
                    albumLikeBadgeView.setBadgeText(String.valueOf(likes));
//                    ToastUtil.show(albumLikeBadgeView.getContext(), R.string.dianzan_fase);
                    albumLikeBadgeView.setSelected(false);
                } else {
                    updateLikesFault(null);
                    return;
                }
            }
            if (likes <= 0) {
                albumLikeBadgeView.showBadgeText(false);
//                album_like_badgeView.setVisibility(View.GONE);
            } else {
                albumLikeBadgeView.showBadgeText(true);
//                album_like_badgeView.setVisibility(View.VISIBLE);
            }
            //  album_like_badgeView.setText(String.valueOf(data.supportCount));
            item.setSupportCount(likes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateLikesFault(Object data) {
        if (albumLikeBadgeView.isSelected()) {
            ToastUtil.show(albumLikeBadgeView.getContext(), R.string.cancel_dianzan_fase);
        } else {
            ToastUtil.show(albumLikeBadgeView.getContext(), R.string.dianzan_fail);
        }
    }

//    @Override
//    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        ShareGridClickUtil.ShareGridClickHandle(shareGridDataUtil, position, item, new CatalogItem(), getActivity());
//    }

    @Override
    public void onResume() {
        super.onResume();


    }
}